package cn.com.cbj.rabbitmq.publisher;

import cn.com.cbj.entity.KnowledgeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
/**
 * 确认消费模式-生产者
 * @Author:debug (SteadyJack)
 **/
@Component
public class KnowledgePublisher {
    //定义日志
    private static final Logger log= LoggerFactory.getLogger(KnowledgePublisher.class);
    //定义JSON序列化和反序列化组件实例
    @Autowired
    private ObjectMapper objectMapper;
    //定义读取环境变量的实例
    @Autowired
    private Environment env;
    //定义RabbitMQ操作组件实例
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 基于AUTO机制-生产者发送消息
     * @param info
     */
    public void sendAutoMsg(KnowledgeInfo info){
        try {
            //判断对象是否为NULL
            if (info!=null){
                //设置消息的传输格式
                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                //设置交换机
                rabbitTemplate.setExchange(env.getProperty("mq.auto.knowledge.exchange.name"));
                //设置路由
                rabbitTemplate.setRoutingKey(env.getProperty("mq.auto.knowledge.routing.key.name"));
                //创建消息。其中，对消息设置了持久化策略
//                Message message= MessageBuilder.withBody(objectMapper.
//                        writeValueAsBytes(info))
//                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
//                        .build();
                //发送消息
                rabbitTemplate.convertAndSend(info);
                log.info("基于AUTO机制-生产者发送消息-内容为：{} ",info);
            }
        }catch (Exception e){
            log.error("基于AUTO机制-生产者发送消息-发生异常：{} ",info,e.fillInStackTrace());
        }
    }
}
